package cn.sql_session.utils;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class SqlSessionThreadSecurityUtils {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory = null;

    // 构造函数私有
    private SqlSessionThreadSecurityUtils() {

    }

    // 读取配置文件
    static {

    }


    /**
     * 获取SqlSession
     *
     * @return
     */
    public static SqlSession getSqlSession() {

        SqlSession sqlSession = threadLocal.get();  // 从当前线程获取
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);  // 将sqlSession与当前线程绑定
        }
        return sqlSession;
    }

    /**
     * 关闭SqlSession
     */
    public static void close() {
        SqlSession sqlSession = threadLocal.get();  // 从当前线程获取
        if (sqlSession != null) {
            sqlSession.close();
            threadLocal.remove();
        }
    }
}
